package org.example.seata.common.core.holder;

import cn.hutool.core.util.StrUtil;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hzq
 * @date 2021/12/18 10:13
 */
@Component
public class TenantFilter extends OncePerRequestFilter implements OrderedFilter {

    /**
     * 租户id参数名
     */
    private static final String TENANT_ID = "TENANT_ID";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 从请求头里获取租户id
        String tenantId = request.getHeader(TENANT_ID);
        // 从请求参数里获取租户id
        if (StrUtil.isBlank(tenantId)) {
            tenantId = request.getParameter(TENANT_ID);
        }
        if (StrUtil.isNotBlank(tenantId)) {
            try {
                TenantHolder.set(new Integer(tenantId));
            } catch (NumberFormatException e) {
                // ignored
            }
        }
        filterChain.doFilter(request, response);
        // 移除租户信息
        TenantHolder.remove();
    }

    @Override
    public int getOrder() {
        // 优先于Security过滤器
        return SecurityProperties.DEFAULT_FILTER_ORDER - 100;
    }
}
